import os,sys,string,math, shutil,DB, bpnn
try:
    import numpy
    import AnalysisTime
    import scipy
    import scipy.stats
    import matplotlib
    import matplotlib.pyplot
    from pylab import *
    import pylab
#    import plot_settings as ps
except :
    pass
import testAll, DescriptionParser
import Configuration
from Configuration import Configuration as cf

config = cf()

fontsize = 13;
cloudPath = "cloud_test_result"
def getTurnAndFactor(filename):
    turn = string.atoi(filename[0:filename.find("_")])
    factor = string.atoi(filename[filename.find("_") + 1: filename.find(".")])
    return(turn, factor)

def getFloatCputime(cputime):
    retval = 0
    words = string.split(cputime, ":")
    l = len(words)
    for i in xrange(0, l/1):
        curval = string.atof(words[i])
        for j in xrange(0, l-i-1):            
            curval = curval * 60 
        retval = retval + curval
    return retval *1.0

def plot(expName,expId, isSmooth=False):
    command = "gnuplot -e "
    content = "set output "
    dir = os.path.join("..", "..", cloudPath, expName, "analysis")
    for filename in os.listdir(dir):
        if filename.find("eps") <0 and config.isFinalResultFile(expId, expName, filename):
            filename = os.path.join(dir, filename)
            cmd = command + "\" set term postscript eps enhanced color; " + content + "'" + filename + "cpu.eps'" +";" 
            cmd = cmd + "set title 'CPU usage'; "
            cmd = cmd + "set xlabel 'time(s)'; "
            cmd = cmd + "set ylabel 'cpu usage(%)'; "
            cmd = cmd + "set y2label 'Memory usage(MB)'; "
            cmd = cmd + "set yrange[0:100];"
            cmd = cmd + "set y2range[0:300000];"
            cmd = cmd + "set y2tics 0, 50000;"
            cmd = cmd + "set ytics nomirror;"
            addon = ""
            if isSmooth == True:
                addon = "smooth csplines "
            cmd = cmd + "plot '" + filename + "' using 1:2 " + addon + "axis x1y1, '" + filename + "' using 1:3 " + addon + "axis x1y2;"
#            cmd = cmd + content + "'" + filename + "memory.eps'" +";"
#            cmd = cmd + "set title 'Memory consumption'; "
#            cmd = cmd + "set xlabel 'time(s)'; "
#            cmd = cmd + "set ylabel 'VM memory'; "
#            cmd = cmd + "plot '" + filename + "' using 1:3; "
#            cmd = cmd + "\""
            print cmd
            os.system(cmd)

def getLegend(expName, factor):
    if expName == "1a2":
        return "%d * %d"%(2**factor, 2**factor)
    if expName == "1a1" or expName == "1a6" or expName == "1a7" or expName == "2a7" or expName == "4a7" or expName == "4a7-1024":
        return "%d AIs"%factor
    if expName == "1a3":
        return "economic level %d"%factor
    if expName == "1a5":
        ret =  Configuration.moreAICommands[factor-1]
        if ret.find("\"")>=0:
            ret = string.strip(ret, "\"")
        return ret

"""
Each factor only 10 lines are printed
"""
def plotTogether(expId, expName,lowTurn, upperTurn, low , upper, startTime = 0, endTime = 2500, isSmooth=True):
    command = "gnuplot -e "
    content = "set output "
    dir = os.path.join("..", "..", cloudPath, expName, "analysis")
    cmd1 = command + "\" set terminal png; " + content + "'" + os.path.join(dir,"%d_"%expId + expName + "_cpu_%d_%d_%d_%d.png"%(lowTurn, upperTurn,low,upper)) +"';" 
    cmd1 = cmd1 + "set title 'CPU usage'; "
    cmd1 = cmd1 + "set xrange[0:%d]; "%endTime
    cmd1 = cmd1 + "set xlabel 'time(s)'; "
    cmd1 = cmd1 + "set ylabel 'cpu usage'; "
#    cmd = cmd + "plot '" + filename + "' using 1:2, "
#    cmd = cmd + ";"
    cmd1 = cmd1 + "plot "
    cmd2 = ""
    cmd2 = cmd2 + content + "'" + os.path.join(dir,"%d_"%expId + expName + "_memory_%d_%d_%d_%d.png"%(lowTurn, upperTurn, low,upper)) +"';"
    cmd2 = cmd2 + "set xrange[0:%d]; "%endTime
    cmd2 = cmd2 + "set title 'Memory consumption'; "
    cmd2 = cmd2 + "set xlabel 'time(s)'; "
    cmd2 = cmd2 + "set ylabel 'VM memory(KB)'; "
#    cmd2 = cmd2 + "plot '" + filename + "' using 1:3; "
#    cmd2 = cmd2 + "\""
    cmd2 = cmd2 + "plot "
    for turn in xrange(lowTurn, upperTurn+1/1):
        for i in xrange(low, upper+1/1):
            total = 0
            filenameTemplate = config.getCpuMemFileNameTemplate(expId, expName, i)
            print filenameTemplate
          
            for filename in os.listdir(dir):
                if filename.find(filenameTemplate) < 0:
                    continue
#                print filename
                total = total + 1
                if total == 2:
                    break
                fn = getLegend(expName, i)
    #            filename = "%d_%d.txt_simplified"%(turn,i)
    #            fn = filename[filename.find("_")+1: filename.find(".")]
    #            elif expName.find("1c")>=0:
    #                filename = "%d_"%expId + expName + "_%d_%d_"%(turn,i) + "192.168.0.1" + "_cpu.txt"
                filename = os.path.join(dir, filename)
                cmd1 = cmd1 + " '" + filename + "' using 1:2 title '" + fn + "' smooth csplines,"
                cmd2 = cmd2 + " '" + filename + "' using 1:3 title '" + fn + "' smooth csplines,"
    #            cmd2 = cmd2 + " '" + filename + "' using 1:3,"
    cmd1 = cmd1[0:len(cmd1)-1] + "; "
    cmd2 = cmd2[0:len(cmd2)-1] + "; "
    cmd = cmd1 + cmd2 + "\""
#    print cmd1, cmd2 , cmd
    os.system(cmd)



def plotComparing(expId, expName,lowTurn, upperTurn, low , upper, filename = "", startTime = 0, endTime = 2500, isSmooth=True):
#    for turn in xrange(lowTurn, upperTurn+1/1):
#        plotNetworkTogether(expId, expName,turn, turn, low , upper, filename, startTime , endTime, isSmooth=True)
#        plotTogether(expId, expName,lowTurn, upperTurn, low , upper, startTime, endTime, isSmooth=True)
#    for factor in xrange(low, upper+1/1):
    plotNetworkTogether(expId, expName,lowTurn, upperTurn, low , upper, filename, startTime , endTime, isSmooth=True)
    plotTogether(expId, expName,lowTurn, upperTurn, low , upper, startTime, endTime, isSmooth=True)
"""
set multiplot
set origin 0.0,0.5
set size 0.5,0.5
plot '''
set origin 0.5,0.5
set size 0.5,0.5
plot 
set origin 0.0,0.0
"""
def multiPlotData(expId, expName, lowTurn, upperTurn, low, upper, fileTag):
    cmd = []
    i = 0
    for turn in xrange(lowTurn, upperTurn+1/1):
        print plotData(expId, expName, turn, turn, low, upper, 2,"time(s)", "packets", i, "network")
        i = i + 1
    print ""
    i = 0
    for factor in xrange(low, upper+1/1):
        print plotData(expId, expName, lowTurn, upperTurn, factor, factor, 2, "time(s)", "byte", i, "network")
        i = i + 1


def getOrign(pth):
    cmd = "set origin "
    if pth == 0: 
        cmd = cmd + "0.0,0.5"
    elif pth == 1:
        cmd = cmd + "0.5,0.5"
    elif pth == 2:
        cmd = cmd + "0.0,0.0"
    elif pth ==3:
        cmd = cmd + "0.5,0.0"
    return cmd

def plotData(expId, expName, lowTurn, upperTurn, low, upper, col, xlabel, ylabel, pth, fileTag= ""):
    cmd1 = getOrign(pth)
    cmd1 = cmd1 + "\nset xlabel '" + xlabel + "'"
    cmd1 = cmd1 + "\nset ylabel '" + ylabel + "'"
    cmd1 = cmd1 + "\nset size 0.5,0.5"
    cmd1 = cmd1 + "\nplot"
    dir = os.path.join("..", "test_result", "trunk")
    for turn in xrange(lowTurn, upperTurn+1/1):
        for i in xrange(low, upper+1/1):
            fn = ""
            filename = "%d_"%expId + expName + "_%d_%d"%(turn,i) + "_" + fileTag + ".txt"
            fn = filename[filename.find("_")+1: filename.find(".")]
#            elif expName.find("1c")>=0:
#                filename = "%d_"%id + expName + "_%d_%d_"%(turn,i) + "192.168.0.1" + "_cpu.txt"
            filename = os.path.join(dir, filename)
            cmd1 = cmd1 + " '" + filename + "' using 1:%d title '%d_%d"%(col, turn, i) + "' smooth csplines,"
    cmd1 = cmd1[0:len(cmd1)-1] + "; "
    return cmd1


def plotNetworkTogether(expId, expName,lowTurn, upperTurn, low , upper, filename = "", startTime = 0, endTime = 2500, yrange1 =1, yrange2=200000, isSmooth=True, isLogScale=True):
    command = "gnuplot -e "
    content = "set output "
    dir = os.path.join("..", "..", cloudPath, expName, "network")
    
    graphDir = os.path.join(dir, "graph")
    if os.path.exists(graphDir) == False: 
        os.mkdir(graphDir)
#    filename = os.path.join(dir, filename)
#    cmd = command + "\" set term postscript eps enhanced color; " + content + "'" + filename + "cpu.eps'" +";" 
#    cmd = cmd + "set title 'CPU usage'; "
#    cmd = cmd + "set xlabel 'time(s)'; "
#    cmd = cmd + "set ylabel 'cpu usage(%)'; "
#    cmd = cmd + "set y2label 'Memory usage(MB)'; "
#    cmd = cmd + "set yrange[0:100];"
#    cmd = cmd + "set y2range[0:300000];"
#    cmd = cmd + "set y2tics 0, 50000;"
#    cmd = cmd + "set ytics nomirror;"
#    cmd = cmd + "plot '" + filename + "' using 1:2 axis x1y1, '" + filename + "' using 1:3 axis x1y2;"
    addon = ""
#    if isLogScale == True:
#        addon = "logScale"
    cmd1 = command + "\" set term postscript eps enhanced color; " + content + "'" + os.path.join(graphDir,addon + "%d_"%expId + expName + "_packets_%d_%d_%d_%d.eps"%(startTime, endTime, low,upper)) +"';" 
#    cmd1 = cmd1 + "set title 'Packets flow'; "
    cmd1 = cmd1 + "set xrange[%d:%d]; "%(startTime, endTime)
#    cmd1 = cmd1 + 'set yrange[%d:%d]; '%(yrange1, yrange2)
    cmd1 = cmd1 + "set xlabel 'time(s)'; "
    cmd1 = cmd1 + "set ylabel 'Packets count'; "
#    cmd = cmd + "plot '" + filename + "' using 1:2, "
#    cmd = cmd + ";"
    if isLogScale == True:
        cmd1 = cmd1 + "set logscale y; "
    cmd1 = cmd1 + "plot "
    cmd2 = ""
    cmd2 = cmd2 + content + "'" + os.path.join(graphDir,"%d_"%expId + expName + "_bytes_%d_%d_%d_%d.eps"%(startTime, endTime, low,upper)) +"';"
    cmd2 = cmd2 + "set xrange[%d:%d]; "%(startTime, endTime)
#    cmd2 = cmd2 + "set yrange[%d:%d]; "%(yrange1, yrange2)
    cmd2 = cmd2 + "set xtics %d; "%startTime
#    cmd2 = cmd2 + "set title 'Bytes Flow'; "
    cmd2 = cmd2 + "set xlabel 'time(s)'; "
    cmd2 = cmd2 + "set ylabel 'Bytes'; "
#    cmd2 = cmd2 + "plot '" + filename + "' using 1:3; "
#    cmd2 = cmd2 + "\""
    cmd2 = cmd2 + "plot "
    for turn in xrange(lowTurn, upperTurn+1/1):
        for i in xrange(low, upper+1/1):
            for filename in os.listdir(dir):
                if filename.find("%d_"%expId + expName+ "_%d_"%i) < 0 or filename.find("network") <0 or filename.endswith(".txt") == False:
                    continue
                sentence1 = ""
                sentence2 = ""
                fn = ""
    #            filename = "%d_%d_network.txt"%(turn,i)
                fn = getLegend(expName, i)
    #            elif expName.find("1c")>=0:
    #                filename = "%d_"%id + expName + "_%d_%d_"%(turn,i) + "192.168.0.1" + "_cpu.txt"
                filename = os.path.join(dir, filename)
                print filename, fn
                sentence1 =  sentence1 + " '" + filename + "' using 1:2 title ' " + fn
                sentence2 = " '" + filename + "' using 1:3 title ' " + fn 
                if(isSmooth):
                    sentence1 = sentence1 +  "' smooth bezier with linespoints,"
                    sentence2 = sentence2 +  "' smooth bezier with linespoints,"
                else:
                    sentence1 = sentence1 + "',"
                    sentence2 = sentence2 + "',"
        #            cmd2 = cmd2 + " '" + filename + "' using 1:3,"
#                sentence1 = sentence1 + " '" + filename + "' using 1:2 with steps 1000,"

                cmd1 = cmd1 + sentence1
                cmd2 = cmd2 + sentence2
    cmd1 = cmd1[0:len(cmd1)-1] + "; "
    cmd2 = cmd2[0:len(cmd2)-1] + "; "
    cmd = cmd1 + cmd2 + "\""
    cmd2 = string.replace(cmd2, ";", "\n")
    print cmd2
#    print cmd
#    print cmd1, cmd2 , cmd
    os.system(cmd)


def boxplotOfSingleFactor(expId, expName, factor, col, isShow = True, additionName = ""):
    dir = os.path.join("..", "..", cloudPath, expName)
    childDir = os.path.join(dir, "analysis")
    filenameTemplate = config.getCpuMemFileNameTemplate(expId, expName, factor)
    data = [[]]
    for filename in os.listdir(childDir):
        if filename.find(filenameTemplate) < 0: continue
        print filename
        d = []
        file = open(os.path.join(childDir,filename))
        lines = file.readlines()
        times = string.split(lines[0])
#            print times
#            print math.floor(string.atof(times[0])), math.floor(string.atof(times[1]))
        firsttime = pretime = string.atof(times[0])
        count = 1 
        total1 = total2 = 0
        for i in xrange(1, len(lines)/1):
                tuple = string.split(lines[i])
                time = string.atof(tuple[0])
                if len(data) < math.floor(time) + 1:
                    data.append([])
                else:
                    data[int(math.floor(time))].append(string.atof(tuple[col]))
    matplotlib.pyplot.boxplot(data, 0, "")
    if col == 1: 
        matplotlib.pyplot.ylabel("CPU usage(%)")
    elif col == 2:
        matplotlib.pyplot.ylabel("Memory usage(MB)")
#    matplotlib.pyplot.fill_between(x, y1, y2, where, hold)
    if expName == "1a1":
        matplotlib.pyplot.xlabel("Time(second)")
        if col == 1:
            matplotlib.pyplot.title("CPU usage change with time when #AI=%d"%factor)
        elif col == 2:
            matplotlib.pyplot.title("Memory usage change with time when #AI=%d"%factor)
    elif expName == "1a2":
        matplotlib.pyplot.xlabel("Map Size 2^%d"%factor)
    elif expName == "1a3":
        matplotlib.pyplot.xlabel("Increasing industry level")
    elif expName == "1a4":
        matplotlib.pyplot.xlabel("16 AIs and 2048*2048 Map")
#    expName + "_(%d to %d)_timeSeries.png"%(1,16)
    filename = "%d"%expId + "_%d_"%factor + expName + "_boxplot_%d"%col + ".eps"
#    filename = "%d"%expId + "_" + expName + "_boxplot_%d"%col + ".svg"
    filename = os.path.join(childDir, filename);
    savefig(filename, dpi=600);
    
    if isShow == True:
        show()

color3 = ['#000000', '#FF0000','#FFFF00','#802A2A', '#0000FF', '#00C78C','#00FF00', '#A020F0']
colors2 = ['#B0E0E6', '#00FFFF', '#4169E1', '#385E0F', '#00FF00', '#BDFCC9', '#9933FA', '#00C78C',
           '#7CFC00', '#0000FF', '#D2B48C', '#5E2612', '#BC8F8F', '#FF6100', '#FF9912', '#FFD700']
colors = ['#E3CF57', '#FFD700', '#E3A869', '#ED9121', '#FF8000', '#F5DEB3', '#A39480', '#873324', '#FF7D40',
          '#BC8F8F', '#734A12', '#F4A460', '#4169E1', '#87CEEB', '#00FFFF', '#00FF00', '#00C957']
colors4 = ['#C0C0C0', '#B22222', '#00FF00', '#4169E1', '#FFFF00']

#testAll.minVars = { "1a1":1, "1a2":6, "1a3":1, "1a4":1, "1a5":1, "1c":1, "1a6-256":1, "1a6-1024":1, "1a6-2048":1, "1a6":1, "2a6":16, "3a6":1}
#testAll.maxVars = { "1a1":16, "1a2":11, "1a3":4, "1a4":1, "1a5":16, "1c":4, "1a6-256":4, "1a6-1024":16, "1a6-2048":16, "1a6":16, "2a6":50, "3a6":16}
xtitle = {"1a1":"# of AIs", "1a2":"Width of Map", "1a3":"Industrial Level","1a4":"", "1a5":"AI Identifier", "1a6": "Number of AIs", "1a7":"Number of AIs",
          "1a8":"Increasing quantity of sea and lake under different terrain types", "1a9":"Map Size", "1a10":"Number of Maximal Road Vehicles", "1a7-5": "Number of AIs", "1a7-5-1024":"Number of AIs", "4a7-1024":"Number of Remote AI Players"}

def get1a11XLabel(expName):
    if expName.find("1a11_0_0")>=0:
        return "a) very low quantity of sea and lake"
    if expName.find("1a11_0_1") >=0:
        return "b) low quantity of sea and lake"
    if expName.find("1a11_0_2")>=0:
        return "c) medium quantity of sea and lake"
    if expName.find("1a11_0_3")>=0:
        return "d) high quantity of sea and lake"

def getXtitleOfBoxPlot(expName):
    if expName.find("1a11") >=0:
        return get1a11XLabel(expName)
    ret = xtitle.get(expName)
    if ret != None:
        return ret
    else: return "no xlabel"
def cpu_usage_mem_boxplot(expName, isShow=False, isNetwork=False):
    i = 0
    for col in (1,2):
        d = []
        matplotlib.pyplot.clf()
#        print DescriptionParser.getMinVarOfExp(expName), DescriptionParser.parseConfigureFile(expName)
        for factor in DescriptionParser.getFactors(expName): 
            print "-------------------------------------------------------------------------------------------"
            print "get Data ", factor
            data = getData(expName, col, factor, False, isShow, False, isNetwork)
#            d.append(data[100:])
            if isNetwork == True:
                d.append(data[100:])
            else:              
                d.append(data)            
            print "----------------------------------------------------------------------------------------------"
#            color = colors4[i % len(colors4)]
            i = i + 1
#        print len(d)\
        matplotlib.pyplot.axes([0.1,0.1,0.85,0.85],frameon = True) 
#        matplotlib.pyplot.axes([0.08,0.1,0.9,0.88],frameon = True) 
        matplotlib.pyplot.boxplot(d, 0, "")

        xt = getXtitleOfBoxPlot(expName)
        if(isNetwork==True):
            xt = "Number of Remote AI Players"
        if isNetwork == False:
            if col == 1:
                suffix(expName, col, isShow,"", "", "cpu_usage_boxplot", isNetwork)
            else :
                suffix(expName, col, isShow,"", "","memory_boxplot", isNetwork)
        else:
            if col == 1:
                suffix(expName, col, isShow,xt, "", "packets_boxplot", isNetwork)
            else :
                suffix(expName, col, isShow, xt,"","bytes_boxplot", isNetwork)

def network_byte_packet_boxplot(expName, isShow=False):
    cpu_usage_mem_boxplot(expName, isShow, True)
    
def difference(expName, isShow=False):
    step = 1
    i = 0
    for col in (1,2):
        for factor in range(DescriptionParser.getMinVarOfExp(expName), DescriptionParser.parseConfigureFile(expName), step):
            data = getData(0, expName, col, factor, False,False, True)
            for i in xrange(0, len(data)):
                for j in xrange(i+1, len(data)):    
                    print AnalysisTime.correlationOfTwoVector(data[i], data[j])

def getTiles(expName):
    if expName == "1a6":
        return 512 ** 2
    if expName == "1a6-1024":
        return 1024**2
    if expName == "1a6-2048":
        return 2048 ** 2
    if expName == "1a6-256":
        return 256 ** 2
    
def player_per_tiles_cpu_time_walkclock_barplot(isShow=False):
    i = 0
    expNames = ["1a6-256","1a6", "1a6-1024"]
    for col in [3,0]:
        matplotlib.pyplot.clf()
        d = {0.0:[]}
        names = {0.0:"abc"}
        for expName in expNames:
            for factor in range(DescriptionParser.getMinVarOfExp(expName), DescriptionParser.parseConfigureFile(expName), 1):
                data = getTimeData(expName, col, factor)
                tiles = getTiles(expName)
                if d.get(tiles/factor) == None:
                    d[tiles/factor] = data
                    names[tiles/factor] = "%d/%d"%(tiles, factor)
                    print tiles, factor
                else:
                    d[tiles/factor].extend(data)
        x = [] 
        y = []
        e = []
        keys = numpy.sort(d.keys())
        print "\n\n\n\n\n------------------------\n\n\n\n\n\n"
        
        for i in xrange(0, len(keys)):
            k = keys[i]
            if k == 0.0 : continue
            ty = d[k]
            print len(ty)
            err = scipy.stats.sem(ty)
            my = numpy.mean(ty)
            e.append(err) #sem is stderr
            x.append(k)
            y.append(my)
            
            print names[k], k, my , err
        AnalysisTime.barplot_witherror(x, y, e)
        if col == 0:
            suffix("Tiles per player", col, isShow, "Tiles per player", "CPU wall clock time tiles per player", "cpu_wallclock_time_barplot")
        elif col == 3 :
            suffix("Tiles per player", col, isShow, "Tiles per player", "CPU Time change with tiles per player","cpu_time_barplot")

    
def player_per_tiles(isShow = False):
    return True

def analysisTimeFactor(expName, timeSlot = 1000):
    for col in [1,2]:
        data = getData(expName, col, 1, True, False,0)
        showData = []
        step = len(data) // timeSlot
        print "---------------------------------"
        for i in range(0, step):
            t = []
            for pth in range(1000*i, 1000 * (i+1) ):
                t.extend(data[pth])
            print len(t)
            print "---------------------------------"

            showData.append(t)
        matplotlib.pyplot.boxplot(showData, 0, "")
        if col == 1:
            suffix(expName, col, False, "Second(per 1000s)", "CPU usage ", "cpu_usage_withTime_boxplot")
        else :
            suffix(expName, col, False, "Second(per 1000s)", "Memory usage ","memory__withTime_boxplot")
    return True

def cpu_usage_mem_min_median_max_timeseries( expName, isShow=False):
    print "---------------------------------------------------------"
    print "cpu_usage_mem_min_median_max_timeseries " + expName
    step = (DescriptionParser.parseConfigureFile(expName)-1 - DescriptionParser.getMinVarOfExp(expName))/len(colors4)
    if step == 0 : step = 1 #design for 1a4
    pth = len(colors4) -1
    for col in (1,2):
        matplotlib.pyplot.clf()
        for factor in range(DescriptionParser.parseConfigureFile(expName)-1, DescriptionParser.getMinVarOfExp(expName) -1 , -step):
            data = getData(expName, col, factor, True, isShow, 0)
            c = colors4[pth % len(colors4)]
            min = []
            max = [] 
            median = []
            for i in xrange(0, len(data)):
                if len(data[i]) == 0 : continue
                max.append(scipy.stats.tmax(data[i], None))
                min.append(scipy.stats.tmin(data[i], None))
                median.append(numpy.median((data[i])))
            matplotlib.pyplot.fill_between(xrange(0, len(max)), max, color = c)
            matplotlib.pyplot.plot([10], [0], color =c , label = "%d"%factor)
            legend()
            pth = pth - 1
            if pth == 0:
                pth = len(colors4) -1
        if col == 1:
            suffix(expName, col, isShow, "Time(Second)", "CPU Usage", "cpu_max_timeseries")
        elif col == 2:
            suffix(expName, col, isShow, "Time(Second)", "Memory Usage", "memory_max_timeseries")
    print "---------------------------------------------------------"

def time_boxplot(expName, col, isShow=False):
    matplotlib.pyplot.clf()
    d = []
    for factor in DescriptionParser.getFactors(expName):
        data = getTimeData(expName, col, factor)
        d.append(data)
    return d

def cpu_time_boxplot(expName, isShow=False):
    d= time_boxplot(expName, 3, isShow)
    matplotlib.pyplot.axes([0.08,0.1,0.9,0.88],frameon = True) 
    matplotlib.pyplot.boxplot(d, 0, "")
    suffix(expName, 3, isShow, "","", "cpu_time")

def cpu_walkclock_boxplot(expName, isShow=False):
    d = time_boxplot(expName, 0, isShow)
#    matplotlib.pyplot.axes([0.12,0.08,0.8,0.9],frameon = True) 
    matplotlib.pyplot.boxplot(d, 0, "")
    exp_walkclock_SpecialFigure(expName)
    suffix(expName, 4, isShow, "" , "", "cpu_walkclock_boxplot")

def cpu_walkclock_errorBar(expName, isShow=False):
    d = time_boxplot(expName, 0, isShow)
#    matplotlib.pyplot.axes([0.12,0.08,0.8,0.9],frameon = True) 
    dx = [1, 2,4,8,16,32,64,128]
    x = np.array(dx);
    y= [];
    yerror = [];
    plt.figure()

    for i in range(0, len(d)):
        data = np.array(d[i]);
        mean = np.mean(data);
        standardError = scipy.stats.sem(data);
        y.append(mean)
        yerror.append(standardError);

    plt.errorbar(x, np.array(y), yerr=np.array(yerror))
    suffix(expName, 4, isShow, "" , "", "cpu_walkclock_boxplot")
    
    
def errorBar(dx, dy):
    x = np.array(dx);
    y = np.array(dy)
    # example variable error bar values
    yerr1 = scipy.stats.sem(y);
#    xerr = 0.1 + yerr
    # First illustrate basic pyplot interface, using defaults where possible.
    plt.figure()
    plt.errorbar(x, y, yerr=yerr1)
#    plt.title("Simplest errorbars, 0.2 in x, 0.4 in y")

def exp_walkclock_SpecialFigure(expName):
    if expName == "1a7":
#        matplotlib.pyplot.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25)
#        matplotlib.pyplot.figtext(0.155, 0.8, DescriptionParser.terrain_type[0])
#        matplotlib.pyplot.figtext(0.4, 0.8, DescriptionParser.terrain_type[1])
#        matplotlib.pyplot.figtext(0.605, 0.8, DescriptionParser.terrain_type[2])
#        matplotlib.pyplot.figtext(0.77, 0.8, DescriptionParser.terrain_type[3])
#        for label in ax.xaxis.get_ticklabels():
#            label.set_color('red')
#            label.set_rotation(45)
#            label.set_fontsize(7)
#            n = numpy.array(DescriptionParser.getFactors(expName))
#            matplotlib.pyplot.axes([0.1,0.1,0.9,0.9],frameon = True) 

        n = numpy.array([0, 100, 200, 300, 400 , 500 , 600, 700, 825, 865, 1000, 1100, 1200, 1300, 1400,1500])
        x = ["0", "100", "200", "300", "400", "500", "600", "700", "825", "865", "1000", "1100", "1200", "1300", "1400", "1500"]
        matplotlib.pyplot.yticks(n, x)
        matplotlib.pyplot.ylim([0, 1500])
        matplotlib.pyplot.axvline(x=65, linestyle="-.")
#        matplotlib.pyplot.axhline(y=825, linestyle="-.")
#        matplotlib.pyplot.axhline(y=865, linestyle="-.")
        matplotlib.pyplot.axhspan(825, 865, color="0.75")
        matplotlib.pyplot.figtext(0.50, 0.85, "Reduced gameplay experience")
#        matplotlib.pyplot.annotate(100, 825, "Reduced gameplay experience")
        matplotlib.pyplot.figtext(0.5, 815.0/1500.0, "Playable Execution Time")

    if expName == "1a2":
        n = numpy.array([1, 2, 3, 4, 5 , 6 , 7])
        x = ["64", "128", "256", "512", "1024","2048", "4096"]
        matplotlib.pyplot.xticks(n, x)



#        n = numpy.array([800, 825, 865, 900, 1000, 1100, 1200, 1300, 1400,1500])
#        x = ["800", "825", "865", "900", "1000", "1100", "1200", "1300", "1400", "1500"]
#        matplotlib.pyplot.yticks(n, x)
#        matplotlib.pyplot.axvline(x=65, linestyle="-.")
##        matplotlib.pyplot.axhline(y=825, linestyle="-.")
##        matplotlib.pyplot.axhline(y=865, linestyle="-.")
#        matplotlib.pyplot.axhspan(825, 865, color="0.75")
#        matplotlib.pyplot.figtext(0.50, 0.8, "Reduced gameplay experience")
##        matplotlib.pyplot.annotate(100, 825, "Reduced gameplay experience")
#        matplotlib.pyplot.figtext(0.5, 0.125, "Playable Execution Time")

        
def linear_prediction(expName, col, isShow=False):
    matplotlib.pyplot.clf()
    d = []
    m = []
    for factor in DescriptionParser.getFactors(expName):
        data = getTimeData(expName, col, factor)
        d.append(data)
        m.append(numpy.mean(data))
    x = DescriptionParser.getFactors(expName)
    return x,m

def cpu_walkclocktime_linear_prediction(expName, isShow=False):
    x, m = linear_prediction(expName, 0, isShow=False)
    AnalysisTime.linearRegression(x, m, expName + "_cpu_walkclock_linear_prediction", 5, isShow)
    
def cpu_time_linear_prediction(expName, isShow=False):
    x, m = linear_prediction(expName, 3, isShow=False)
    AnalysisTime.linearRegression(x, m, expName + "_cpu_time_linear_prediction", 5, isShow)

def getTimeData(expName, col,factor):
    dir = os.path.join("..", "..", cloudPath, expName)
    childDir = os.path.join(dir, "analysis")
    filenameTemplate = config.getCpuMemFileNameTemplate(0, expName, factor)
    data = []
    for filename in os.listdir(childDir):
        if filename.find(filenameTemplate) < 0: 
            continue
        file = open(os.path.join(childDir,filename))
        lines = file.readlines()
        l = lines[len(lines)-1]
        tuple = string.split(l)
        data.append(getFloatCputime(tuple[col]))
    return data

def reduceData(stringData):
    data = string.atof(stringData)
    if data >=2000:
        data = data/1024
    return data
def getData(expName, col, factor, isGroup=True, isShow=False, isFindDistance=False, isNetwork = False, expId = 0):
    dir = os.path.join("..", "..", cloudPath, expName)
    if isNetwork == True:
        childDir = os.path.join(dir, "network")
    else:
        childDir = os.path.join(dir, "analysis")
    filenameTemplate = config.getCpuMemFileNameTemplate(expId, expName, factor, isNetwork)
    if isGroup == True:
        data = [[]]
    else: 
        data = []
    findDistance = []
    for filename in os.listdir(childDir):
        if filename.find(filenameTemplate) < 0 or filename.endswith("txt") == False: 
            continue
#        print filename.endswith("txt")
        print filename
        if filename == "113_1_node078.txt":
            print filename.find(filenameTemplate)
            print filename.endswith("txt")
        file = open(os.path.join(childDir,filename))
        lines = file.readlines()
        times = string.split(lines[0])
#            print times
#            print math.floor(string.atof(times[0])), math.floor(string.atof(times[1]))
        d = []
        for i in xrange(1, len(lines)/1):
            tuple = string.split(lines[i])
            if(isGroup):
                time = string.atof(tuple[0])
                if len(data) < math.floor(time) + 1:
                    data.append([])
                else:
                    data[int(math.floor(time))].append(reduceData(tuple[col]))
            else: 
                data.append(reduceData(tuple[col]))
            if isFindDistance:
                d.append(reduceData(tuple[col]))
        if isFindDistance:
            findDistance.append(d)
    if isFindDistance:
        return findDistance
    return data
    

def suffix(expName,col, isShow=False, xlabel1 = "", title = "", filename = "", isNetwork=False):
#    yoverride = {
#       'fontsize'            : fontsize,
#       'verticalalignment'   : 'center',
#       'horizontalalignment' : 'right',
#       "weight":"bold"}
#    xoverride = {
#    'fontsize'            : fontsize,
#    'verticalalignment'   : 'top',
#    'horizontalalignment' : 'center',
#    'weight':'bold'
#    }
    yoverride = {
       'fontsize'            : fontsize,
       'verticalalignment'   : 'center',
       'horizontalalignment' : 'right'
     }
    xoverride = {
    'fontsize'            : fontsize,
    'verticalalignment'   : 'top',
    'horizontalalignment' : 'center'
    }
    if expName == "1a10":
#            n = numpy.array(DescriptionParser.getFactors(expName))
            n = numpy.array([1,2,3,4])
            x = ["500", "1000", "1500", "2000"]
            matplotlib.pyplot.xticks(n, x)
    if expName == "1a7":
        x = ["1","2", "4", "8", "16", "32", "64", "128"]
        n = numpy.array([1, 2, 3, 4, 5, 6, 7, 8])
        matplotlib.pyplot.xticks(n, x)
        matplotlib.pyplot.xlim([0, 9])
#        x = ["0","10", "20", "30", "40", "50", "60", "70", "80", "90", "100", "150", "200"]
#        n = numpy.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150 , 200])
#        matplotlib.pyplot.xticks(n, x)
    if isNetwork == False:
        if col == 1: 
            matplotlib.pyplot.ylabel("CPU usage(%)", yoverride)
        elif col == 2:
            matplotlib.pyplot.ylabel("Memory usage(MB)",yoverride)
        elif col == 3:
            matplotlib.pyplot.ylabel("Pure CPU time(second)",yoverride)
        elif col == 4:
            matplotlib.pyplot.ylabel("Exectuion time(second)",yoverride)
    else:
        if col == 1: 
            matplotlib.pyplot.ylabel("Network flow(Packets/s)",yoverride)
        elif col == 2:
            matplotlib.pyplot.ylabel("Network flow(KBytes/s)", yoverride)
        
    
    if xlabel1 == "":
        xlabel = getXtitleOfBoxPlot(expName)
        matplotlib.pyplot.xlabel(xlabel,xoverride)
    else :
        matplotlib.pyplot.xlabel(xlabel1,xoverride)
    matplotlib.pyplot.title(title)
    filename = expName + "_"+ filename + ".eps"
    
    filename = os.path.join("..","cloud",filename);
    savefig(filename, dpi=600);
    if isShow == True:
        show()
        
def minMaxPlotOfSingleFactor(expId, expName, factor, col, isShow = True, additionName = ""):
    dir = os.path.join("..", "..", cloudPath, expName)
    childDir = os.path.join(dir, "analysis")
    filenameTemplate = config.getCpuMemFileNameTemplate(expId, expName, factor)
    data = [[]]
    max = []
    min = [] 
    median = []
    for filename in os.listdir(childDir):
        if filename.find(filenameTemplate) < 0: continue
        print filename
        d = []
        file = open(os.path.join(childDir,filename))
        lines = file.readlines()
        times = string.split(lines[0])
#            print times
#            print math.floor(string.atof(times[0])), math.floor(string.atof(times[1]))
        firsttime = pretime = string.atof(times[0])
        count = 1 
        total1 = total2 = 0
        for i in xrange(1, len(lines)/1):
                tuple = string.split(lines[i])
                time = string.atof(tuple[0])
                if len(data) < math.floor(time) + 1:
                    data.append([])
                else:
                    data[int(math.floor(time))].append(string.atof(tuple[col]))
    import scipy.stats
    import numpy
    for i in xrange(0, len(data)):
        if len(data[i]) == 0 : continue
        max.append(scipy.stats.tmax(data[i], None))
        min.append(scipy.stats.tmin(data[i], None))
        median.append(numpy.median((data[i])))
    matplotlib.pyplot.plot(max)
    matplotlib.pyplot.plot(min)
    matplotlib.pyplot.plot(median)
    if col == 1: 
        matplotlib.pyplot.ylabel("CPU usage(%)")
    elif col == 2:
        matplotlib.pyplot.ylabel("Memory usage(MB)")
#    matplotlib.pyplot.fill_between(x, y1, y2, where, hold)
    if expName == "1a1":
        matplotlib.pyplot.xlabel("Time(second)")
        if col == 1:
            matplotlib.pyplot.title("CPU usage change with time when #AI=%d"%factor)
        elif col == 2:
            matplotlib.pyplot.title("Memory usage change with time when #AI=%d"%factor)
    elif expName == "1a2":
        matplotlib.pyplot.xlabel("Map Size 2^%d"%factor)
    elif expName == "1a3":
        matplotlib.pyplot.xlabel("Increasing industry level")
    elif expName == "1a4":
        matplotlib.pyplot.xlabel("16 AIs and 2048*2048 Map")
#    expName + "_(%d to %d)_timeSeries.png"%(1,16)
    filename = "%d"%expId + "_%d_"%factor + expName + "_minmax_%d"%col + ".eps"
#    filename = "%d"%expId + "_" + expName + "_boxplot_%d"%col + ".svg"
    filename = os.path.join(childDir, filename);
    savefig(filename, dpi=600);
    
    if isShow == True:
        show()


def getCPUandNetworkFilePair(expId, expName, factor):
    
    cpufile = ""
    networkfile = ""
    networkPath = os.path.join("..", "..", cloudPath, expName, "network")
    for file in os.listdir(networkPath):
        if file.find("%d_"%expId + expName + "_%d_"%factor) >=0 and file.find("network") >=0 and file.endswith(".txt"):
            networkfile = file;
            break;
    template = file[len("%d_"%expId + expName + "_%d_"%factor):file.find("network")]
     
    cpuPath = os.path.join("..", "..", cloudPath, expName, "analysis")
    for file in os.listdir(cpuPath):
        if file.find("%d_"%expId + expName + "_%d"%factor) >=0 and file.find("cpu") >=0 and file.endswith(".txt") and file.find(template)>=0:
            cpufile = file
            break    
    ret = (os.path.join(cpuPath,cpufile),os.path.join(networkPath,networkfile))
    print ret
    return ret
def plotTwoDataTogether(expId, expName, factor, startTime, endTime, isSmooth=False):
    command = "gnuplot -e "
    content = "set output "
    f1,f2 = getCPUandNetworkFilePair(expId, expName, factor)
    filename = "%d_"%expId + expName + "_%d"%factor
    cmd = command + "\" set term postscript eps enhanced color; " + content + "'" + filename + "cpunetwork.eps'" +";" 
    cmd = cmd + "set title 'CPU and Bytes'; "
    cmd = cmd + "set xlabel 'time(s)'; "
    cmd = cmd + "set ylabel 'cpu usage(%)'; "
    cmd = cmd + "set y2label 'Bytes usage(B)'; "
    cmd = cmd + "set yrange[0:100];"
    cmd = cmd + "set y2range[0:400000];"
    cmd = cmd + "set y2tics 0, 50000;"
    cmd = cmd + "set ytics nomirror;"
    addon = ""
    if isSmooth == True:
        addon = "smooth csplines"
    cmd = cmd + "plot '" + f1 + "' using 1:2 axis x1y1 " + addon + ", '" + f2 + "' using 1:3 axis x1y2 " + addon+ ";"
#            cmd = cmd + content + "'" + filename + "memory.eps'" +";"
#            cmd = cmd + "set title 'Memory consumption'; "
#            cmd = cmd + "set xlabel 'time(s)'; "
#            cmd = cmd + "set ylabel 'VM memory'; "
#            cmd = cmd + "plot '" + filename + "' using 1:3; "
#            cmd = cmd + "\""
    print cmd
    os.system(cmd)

def getNodeNameInAutoSave(expName, expId=666):
    path = config.getAutoSavePath(expName)
    whichYear = config.getAutoSaveYear(expName)
    nodenames = []
    for file in os.listdir(path):
        if file.find("%d"%expId) <0:
            continue
        p1 = file.find("node")
        p2 = file.find("_", p1)
#        print file, p1, p2, file[p1:p2]
        nodename = file[p1:p2]
#        print nodename, nodenames, nodename in nodenames
        if (nodename in nodenames) == False:
            nodenames.append(nodename)
    for factor in DescriptionParser.getFactors(expName):
        print factor
        print "--------------------------------------------------"
        for nodename in nodenames:
            getSingleNoderesultInSeveralYear(expName, expId, nodename, factor, 1)
        print "--------------------------------------------------"

#    print nodenames
def getSingleNoderesultInSeveralYear(expName, expId, nodename, factor, pos):
    from ParseSaveFileDumpResult import SaveFileResult
    path = config.getAutoSavePath(expName)
    whichYear = config.getAutoSaveYear(expName)
    nodenames = []
    for year in range(0, whichYear+1):
        filename = "%d_"%expId + expName + "_%d_"%factor+nodename+"_autosave%d.sav_"%year+ "companyScore.txt"
#        print filename
        sr = SaveFileResult()
        if sr.parseSaveFileResult(os.path.join(path, filename)) == True:
            print nodename, sr.data[pos], filename
#    for file in os.listdir(path):
#        if file.find(nodename) <0 or file.find(expId)<0 or file.find(expName)<0:
            
#    for factor in DescriptionParser.getFactors(expName):
#        addon = ""
#        filenameTemplate = addon + expName + "_%d_"%factor  
#        t = [] 
#        for file in os.listdir(path):
#            if file.find(filenameTemplate) <0 or file.endswith("companyScore.txt") == False or file.find("autosave%d.sav"%whichYear)<=0:
#                continue
def getScore(expName, pos,getAll=True):
    yoverride = {
       'fontsize'            : fontsize,
       'verticalalignment'   : 'center',
       'horizontalalignment' : 'right',
       "weight":"bold"}
    xoverride = {
    'fontsize'            : fontsize,
    'verticalalignment'   : 'top',
    'horizontalalignment' : 'center',
    'weight':'bold'
    }
    import ParseSaveFileDumpResult
    year = config.getAutoSaveYear(expName)
    data = ParseSaveFileDumpResult.parseSaveFileResultsAll(expName, 0, pos, getAll,year)
#    print len(data)
    for d in data:
        print d
    matplotlib.pyplot.clf()
#    matplotlib.pyplot.axes([0.08,0.1,0.9,0.88],frameon = True) 
    bp = matplotlib.pyplot.boxplot(data, 0, "")
    name = ParseSaveFileDumpResult.name[pos]
    xlabel = getXtitleOfBoxPlot(expName)
    matplotlib.pyplot.xlabel(xlabel,xoverride)
#    matplotlib.pyplot.show()
    x = Configuration.moreAICommands
    n = numpy.arange(len(x))
    matplotlib.pyplot.ylabel(name, yoverride)
#    legend("abc")
    #    matplotlib.pyplot.xticks(n, x)
#    matplotlib.pyplot.show()
    if expName == "1a7":
            x = ["0","10", "20", "30", "40", "50", "60", "70", "80", "90", "100", "150", "200"]
            n = numpy.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150 , 200])
#            n = numpy.arange(len(x))
            matplotlib.pyplot.xticks(n, x)
    if expName == "1a10":
#            n = numpy.array(DescriptionParser.getFactors(expName))
            n = numpy.array([1, 2, 3, 4])
            x = ["500", "1000", "1500", "2000"]
            matplotlib.pyplot.xticks(n, x)
    name = string.replace(name, " ", "_")
    matplotlib.pyplot.savefig("../png/"+ expName + "_" + name + "_%d"%pos+".eps")
"""
different map structure
"""
def _1a8_cpu_usage_mem_boxplot(isShow=False, isNetwork=False):
    step = 1
    i = 0
    expName = "1a8"
    for col in (1,2):
        d = []
        matplotlib.pyplot.clf()
        print DescriptionParser.getFactors(expName)
        for factor in DescriptionParser.getFactors(expName):
            data = getData(expName, col, factor, False, isShow, isNetwork)
            d.append(data)
#            color = colors4[i % len(colors4)]
            i = i + 1
#        print len(d)
        fig = matplotlib.pyplot.figure()
        ax = fig.add_subplot(111)
        p1 = ax.boxplot(d, 0, "")
        print len(d)
#        x = ["", "sea very low", "sea low", "sea medium", "sea high", "sea very low", "sea low", "sea medium", "sea high",
#             "sea very low", "sea low", "sea medium", "sea high", "sea very low", "sea low", "sea medium", "sea high"]
        x = ["","0", "1", "2", "3", "0", "1", "2", "3", "0", "1", "2", "3", "0", "1", "2", "3", ""]
        n = numpy.arange(len(x))
        matplotlib.pyplot.xticks(n, x)
        matplotlib.pyplot.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25)
        matplotlib.pyplot.figtext(0.155, 0.8, DescriptionParser.terrain_type[0])
        matplotlib.pyplot.figtext(0.4, 0.8, DescriptionParser.terrain_type[1])
        matplotlib.pyplot.figtext(0.605, 0.8, DescriptionParser.terrain_type[2])
        matplotlib.pyplot.figtext(0.77, 0.8, DescriptionParser.terrain_type[3])
#        for label in ax.xaxis.get_ticklabels():
#            label.set_color('red')
#            label.set_rotation(45)
#            label.set_fontsize(7)
        matplotlib.pyplot.axvline(x=4.5)
        matplotlib.pyplot.axvline(x=8.5)
        matplotlib.pyplot.axvline(x=12.5)
        xt = getXtitleOfBoxPlot(expName)
        if isNetwork == False:
            if col == 1:
                suffix(expName, col, isShow, xt, "", "cpu_usage_boxplot")
            else :
                suffix(expName, col, isShow, xt, "","memory_boxplot")
        else:
            if col == 1:
                suffix(expName, col, isShow, xt, "", "bytes_boxplot")
            else :
                suffix(expName, col, isShow, xt, "","packets_boxplot")

def _1a12_cpu_usage_mem_boxplot(isShow=False, isNetwork=False):
    step = 1
    i = 0
    expName = "1a12"
    for col in (1,2):
        d = []
        matplotlib.pyplot.clf()
        print DescriptionParser.getFactors(expName)
        for factor in DescriptionParser.getFactors(expName):
            if factor % 5 == 4:
                continue
            data = getData(expName, col, factor, False, isShow, isNetwork)
            d.append(data)
#            color = colors4[i % len(colors4)]
            i = i + 1
#        print len(d)
        fig = matplotlib.pyplot.figure()
        ax = fig.add_subplot(111)
        p1 = ax.boxplot(d, 0, "")
        print len(d)
#        x = ["", "sea very low", "sea low", "sea medium", "sea high", "sea very low", "sea low", "sea medium", "sea high",
#             "sea very low", "sea low", "sea medium", "sea high", "sea very low", "sea low", "sea medium", "sea high"]
        x = ["","0", "1", "2", "3", "0", "1", "2", "3", "0", "1", "2", "3", "0", "1", "2", "3", "0", "1", "2", "3", ""]
        n = numpy.arange(len(x))
        matplotlib.pyplot.xticks(n, x)
        matplotlib.pyplot.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25)
        matplotlib.pyplot.figtext(0.155, 0.8, "None Industries")
        matplotlib.pyplot.figtext(0.4, 0.8, "Very Low Industries")
        matplotlib.pyplot.figtext(0.605, 0.8, "Low Industries")
        matplotlib.pyplot.figtext(0.77, 0.8, "Normal Industries")
        matplotlib.pyplot.figtext(0.77, 0.8, "High Industries")
#        for label in ax.xaxis.get_ticklabels():
#            label.set_color('red')
#            label.set_rotation(45)
#            label.set_fontsize(7)
        matplotlib.pyplot.axvline(x=4.5)
        matplotlib.pyplot.axvline(x=8.5)
        matplotlib.pyplot.axvline(x=12.5)
        xt = getXtitleOfBoxPlot(expName)
        if isNetwork == False:
            if col == 1:
                suffix(expName, col, isShow, xt, "", "cpu_usage_boxplot")
            else :
                suffix(expName, col, isShow, xt, "","memory_boxplot")
        else:
            if col == 1:
                suffix(expName, col, isShow, xt, "", "bytes_boxplot")
            else :
                suffix(expName, col, isShow, xt, "","packets_boxplot")

def HowmanyExps(path=config.getPath()):
    data = []
    for filename in os.listdir(path):
        if os.path.isdir(os.path.join(path,filename)):
            ret = HowmanyExps(os.path.join(path,filename))
            data.extend(ret)
        elif filename.endswith("log.txt"):
            try:
                file = open(os.path.join(path,filename))
                lines = file.readlines()
                year = string.atoi(lines[0])
                start = string.atof(lines[2])
                end = string.atof(lines[4+year])
                l = lines[len(lines)-1]
                tuple = string.split(l)
                data.append(end-start)
            except:
                pass
    return data

def _1a11_5y_All(pos,getAll=True): 
    import ParseSaveFileDumpResult
    matplotlib.pyplot.clf()
    matplotlib.pyplot.axes([0.08,0.1,0.9,0.88],frameon = True) 
    fig = matplotlib.pyplot.figure()
    ax = fig.add_subplot(111)
    data = []
    i = 0
#    "quick-1a11_0_1-5y", "quick-1a11_0_2-5y",
    expNames = ["quick-1a11_0_0-5y","quick-1a11_0_3-5y"]
    colors = ["r", "b", "g", "y"]
#    expNames = ["quick-1a11_0_0-5y", "quick-1a11_0_1-5y", "quick-1a11_0_2-5y", "quick-1a11_0_3-5y"]
    pics = []
    legends = []
    w = 0.9
    for expName in expNames:
        year = config.getAutoSaveYear(expName)
        d = ParseSaveFileDumpResult.parseSaveFileResultsAll(expName, 0, pos, getAll,year)
        data.append(d)
        x = []
        y = []
        e = []
        p = 0
        for info in d:
            err = scipy.stats.sem(info)
            my = numpy.mean(info)
            e.append(err) #sem is stderr
            x.append(p*len(expNames) + i)
            y.append(my)
            p = p + 1
        print x, y
        p  = ax.bar(numpy.array(x), y, yerr=e, width=w, color = colors[i])
        name = getXtitleOfBoxPlot(expName).replace(" ", "_")
        pics.append(p[0])
        legends.append(name)
        i = i + 1
    transformData = []
    matplotlib.pyplot.legend(tuple(pics), tuple(legends))

#    plt.legend( (p1[0], p2[0]), ('Men', 'Women') )


    xtics = []
    for i in DescriptionParser.getFactors(expName):
        j = (i-1) *len(expNames) + len(expNames) * w * 0.5
#        print i-1, len(expNames), w, len(expNames) * w, len(expNames) * w * 0.5
        print j
        xtics.append(j)
    stringXtics=[]
    for i in range(1, len(xtics)+1):
        stringXtics.append("%d"%i)
   
    name = ParseSaveFileDumpResult.name[pos]
    xlabel = "AIs' score in 5 in-game year with Flat Terrain and Different Sea level"
    matplotlib.pyplot.xlabel(xlabel)
#    matplotlib.pyplot.show()
    x = Configuration.moreAICommands
    n = numpy.arange(len(x))
    matplotlib.pyplot.ylabel(name)
#    legend("abc")
    #    matplotlib.pyplot.xticks(n, x)
#    matplotlib.pyplot.show()
    
#            n = numpy.array(DescriptionParser.getFactors(expName))
    n = numpy.array(xtics)
    x = stringXtics
    matplotlib.pyplot.xticks(n, x)
    name = string.replace(name, " ", "_")
    matplotlib.pyplot.savefig("../png/"+ "1a11_differentSealevel" + "_" + name + "_%d"%pos+".eps")


def rondje(pos,getAll=True): 
    import ParseSaveFileDumpResult
    matplotlib.pyplot.clf()
    matplotlib.pyplot.axes([0.08,0.1,0.9,0.88],frameon = True) 
    fig = matplotlib.pyplot.figure()
    ax = fig.add_subplot(111)
    data = []
    i = 0
#    "quick-1a11_0_1-5y", "quick-1a11_0_2-5y",
    expNames = ["quick-1a14-5y","quick-1a15-5y"]
    colors = ["r", "b", "g", "y"]
    labels = ["Single Player", "Two Players"]
    pics = []
    legends = []
    w = 1
    for expName in expNames:
        year = config.getAutoSaveYear(expName)
        d = ParseSaveFileDumpResult.parseSaveFileResultsAll(expName, 0, pos, getAll,year)
        data.append(d)
        x = []
        y = []
        e = []
        p = 0
        for info in d:
            err = scipy.stats.sem(info)
            my = numpy.mean(info)
            e.append(err) #sem is stderr
            x.append(p*len(expNames) + i)
            y.append(my)
            p = p + 1
        print x, y
        p  = ax.bar(numpy.array(x), y, yerr=e, width=w, color = colors[i])
        name = getXtitleOfBoxPlot(expName).replace(" ", "_")
        pics.append(p[0])
        legends.append(labels[i])
        i = i + 1
    transformData = []
    matplotlib.pyplot.legend(tuple(pics), tuple(legends))
    xtics = []
    for i in DescriptionParser.getFactors(expName):
        j = ((i-1) *len(expNames)-1)* w
#                j = (i-1) *len(expNames) + len(expNames) * w * 0.5
#        print i-1, len(expNames), w, len(expNames) * w, len(expNames) * w * 0.5
        print j
        xtics.append(j)
    stringXtics=[]
    for i in range(1, len(xtics)+1):
        stringXtics.append("%d"%i)
   
    name = ParseSaveFileDumpResult.name[pos]
    xlabel = "AI Identifier"
    matplotlib.pyplot.xlabel(xlabel)
#    matplotlib.pyplot.show()
    x = Configuration.moreAICommands
    n = numpy.arange(len(x))
    matplotlib.pyplot.ylabel(name)
#    legend("abc")
    #    matplotlib.pyplot.xticks(n, x)
#    matplotlib.pyplot.show()
    
#            n = numpy.array(DescriptionParser.getFactors(expName))
    n = numpy.array(xtics)
    x = stringXtics
    matplotlib.pyplot.xticks(n, x)
    name = string.replace(name, " ", "_")
    matplotlib.pyplot.savefig("../png/"+ "rondje" + "_" + name + "_%d"%pos+".eps")


def rondjeWhichCompany(pos,getAll=True, whichCompany=-1): 
    import ParseSaveFileDumpResult
    matplotlib.pyplot.clf()
    matplotlib.pyplot.axes([0.08,0.1,0.9,0.88],frameon = True) 
    fig = matplotlib.pyplot.figure()
    ax = fig.add_subplot(111)
    data = []
    i = 0
#    "quick-1a11_0_1-5y", "quick-1a11_0_2-5y",
    expNames = ["quick-1a14-5y","quick-1a15-5y"]
    colors = ["r", "b", "g", "y"]
    labels = ["Single Player", "Two players"]
    pics = []
    legends = []
    w = 0.9
    orignCompany = -1
    for expName in expNames:
        year = config.getAutoSaveYear(expName)
        d = ParseSaveFileDumpResult.parseSaveFileResultsAll(expName, 0, pos, getAll,year,orignCompany)
        orignCompany = whichCompany
        data.append(d)
        x = []
        y = []
        e = []
        p = 0
        for info in d:
            err = scipy.stats.sem(info)
            my = numpy.mean(info)
            e.append(err) #sem is stderr
            x.append(p*len(expNames) + i)
            y.append(my)
            p = p + 1
        print x, y
        p  = ax.bar(numpy.array(x), y, yerr=e, width=w, color = colors[i])
        name = getXtitleOfBoxPlot(expName).replace(" ", "_")
        pics.append(p[0])
        legends.append(labels[i])
        i = i + 1
    transformData = []
    matplotlib.pyplot.legend(tuple(pics), tuple(legends))
    xtics = []
    for i in DescriptionParser.getFactors(expName):
        j = (i-1) *len(expNames) + len(expNames) * w * 0.5
#        print i-1, len(expNames), w, len(expNames) * w, len(expNames) * w * 0.5
        print j
        xtics.append(j)
    stringXtics=[]
    for i in range(1, len(xtics)+1):
        stringXtics.append("%d"%i)
   
    name = ParseSaveFileDumpResult.name[pos]
    xlabel = "AI Identifier"
    matplotlib.pyplot.xlabel(xlabel)
#    matplotlib.pyplot.show()
    x = Configuration.moreAICommands
    n = numpy.arange(len(x))
    matplotlib.pyplot.ylabel(name)
#    legend("abc")
    #    matplotlib.pyplot.xticks(n, x)
#    matplotlib.pyplot.show()
    
#            n = numpy.array(DescriptionParser.getFactors(expName))
    n = numpy.array(xtics)
    x = stringXtics
    matplotlib.pyplot.xticks(n, x)
    name = string.replace(name, " ", "_")
    matplotlib.pyplot.savefig("../png/"+ "rondje_self_%d"%whichCompany + "_" + name + "_%d"%pos+".eps")


def rondje_boxplot(pos,getAll=True): 
    import ParseSaveFileDumpResult
    matplotlib.pyplot.clf()
    matplotlib.pyplot.axes([0.08,0.1,0.9,0.88],frameon = True) 
    fig = matplotlib.pyplot.figure()
    ax = fig.add_subplot(111)
    data = []
    i = 0
#    "quick-1a11_0_1-5y", "quick-1a11_0_2-5y",
    expNames = ["quick-1a14-5y","quick-1a15-5y"]
    colors = ["r", "b", "g", "y"]
    labels = ["Single Player", "Introduce Competitior"]
    pics = []
    legends = []
    w = 0.9
    for expName in expNames:
        year = config.getAutoSaveYear(expName)
        d = ParseSaveFileDumpResult.parseSaveFileResultsAll(expName, 0, pos, getAll,year)
        data.append(d)
    transformData = []
    factors = DescriptionParser.getFactors(expName)
    for factor in factors:
        for i in range(0, len(expNames)):
            print len(factors) * i + (factor-1), len(data)
            transformData.append(data[i][(factor-1)])
            
#    matplotlib.pyplot.legend(tuple(pics), tuple(legends))
    ax.boxplot(transformData, 0, "")
#    plt.legend( (p1[0], p2[0]), ('Men', 'Women') )


    xtics = []
    for i in DescriptionParser.getFactors(expName):
        j = (i-1) *len(expNames) + len(expNames) * w * 0.5
#        print i-1, len(expNames), w, len(expNames) * w, len(expNames) * w * 0.5
        print j
        xtics.append(j)
    stringXtics=[]
    for i in range(1, len(xtics)+1):
        stringXtics.append("%d"%i)
   
    name = ParseSaveFileDumpResult.name[pos]
    xlabel = "AI Identifier"
    matplotlib.pyplot.xlabel(xlabel)
#    matplotlib.pyplot.show()
    x = Configuration.moreAICommands
    n = numpy.arange(len(x))
    matplotlib.pyplot.ylabel(name)
#    legend("abc")
    #    matplotlib.pyplot.xticks(n, x)
#    matplotlib.pyplot.show()
    
#            n = numpy.array(DescriptionParser.getFactors(expName))
    n = numpy.array(xtics)
    x = stringXtics
    matplotlib.pyplot.xticks(n, x)
    name = string.replace(name, " ", "_")
    matplotlib.pyplot.savefig("../png/"+ "rondje_boxplot" + "_" + name + "_%d"%pos+".eps")

def scalability_all_bar(pos,getAll=True): 
    import ParseSaveFileDumpResult
    matplotlib.pyplot.clf()
    matplotlib.pyplot.axes([0.08,0.1,0.9,0.88],frameon = True) 
    fig = matplotlib.pyplot.figure()
    ax = fig.add_subplot(111)
    data = []
    i = 0
#    "quick-1a11_0_1-5y", "quick-1a11_0_2-5y",
    expNames = ["1a7","1a7-1024"]
    colors = ["r", "b", "g", "y"]
    labels = ["512 * 512", "1024 * 1024"]
    pics = []
    legends = []
    w = len(expNames)/2;
    for expName in expNames:
        year = config.getAutoSaveYear(expName)
        d = ParseSaveFileDumpResult.parseSaveFileResultsAll(expName, 0, pos, getAll,year)
        data.append(d)
        x = []
        y = []
        e = []
        p = 0
        for info in d:
            err = scipy.stats.sem(info)
            my = numpy.mean(info)
            e.append(err) #sem is stderr
            x.append(p*len(expNames) + i)
            y.append(my)
            p = p + 1
        print x, y
        p  = ax.bar(numpy.array(x), y, yerr=e, width=w, color = colors[i])
        name = getXtitleOfBoxPlot(expName).replace(" ", "_")
        pics.append(p[0])
        legends.append(labels[i])
        i = i + 1
    transformData = []
    matplotlib.pyplot.legend(tuple(pics), tuple(legends))
    xtics = []
    for i in DescriptionParser.getFactors(expName):
        i = i - DescriptionParser.getMinVarOfExp(expName);
        j = (i *len(expNames))* w + w;
#                j = (i-1) *len(expNames) + len(expNames) * w * 0.5
#        print i-1, len(expNames), w, len(expNames) * w, len(expNames) * w * 0.5
        print j
        xtics.append(j)
    stringXtics=[]
    for i in range(1, len(xtics)+1):
        i = i + DescriptionParser.getMinVarOfExp(expName) - 1;
        stringXtics.append("%d"%i)
   
    name = ParseSaveFileDumpResult.name[pos]
    xlabel = "Number of AIs"
    matplotlib.pyplot.xlabel(xlabel)
#    matplotlib.pyplot.show()
    x = Configuration.moreAICommands
    n = numpy.arange(len(x))
    matplotlib.pyplot.ylabel(name)
#    legend("abc")
    #    matplotlib.pyplot.xticks(n, x)
#    matplotlib.pyplot.show()
    
#            n = numpy.array(DescriptionParser.getFactors(expName))
    n = numpy.array(xtics)
    x = stringXtics
    matplotlib.pyplot.xticks(n, x)
    name = string.replace(name, " ", "_")
    matplotlib.pyplot.savefig("../png/"+ "scalability" + "_" + name + "_%d"%pos+".eps")


def scalability_all_median(pos,getAll=True): 
    import ParseSaveFileDumpResult
    matplotlib.pyplot.clf()
    matplotlib.pyplot.axes([0.08,0.1,0.9,0.88],frameon = True) 
    fig = matplotlib.pyplot.figure()
    ax = fig.add_subplot(111)
    data = []
    i = 0
#    "quick-1a11_0_1-5y", "quick-1a11_0_2-5y",
    expNames = ["1a7","1a7-1024-op40000"]
    colors = ["r", "b", "g", "y"]
    labels = ["512 * 512", "1024 * 1024"]
    pics = []
    legends = []
    w = len(expNames)/2;
    for expName in expNames:
        year = config.getAutoSaveYear(expName)
        d = ParseSaveFileDumpResult.parseSaveFileResultsAll(expName, 0, pos, getAll,year)
        data.append(d)
        x = []
        y = []
        p = 0
        for info in d:
            err = scipy.stats.sem(info)
            my = numpy.median(info)
#            e.append(err) #sem is stderr
            x.append(p*len(expNames) + i)
            y.append(my)
            p = p + 1
        print x, y
        p  = ax.bar(numpy.array(x), y, width=w, color = colors[i])
        name = getXtitleOfBoxPlot(expName).replace(" ", "_")
        pics.append(p[0])
        legends.append(labels[i])
        i = i + 1
    transformData = []
    matplotlib.pyplot.legend(tuple(pics), tuple(legends))
    xtics = []
    for i in DescriptionParser.getFactors(expName):
        i = i - DescriptionParser.getMinVarOfExp(expName);
        j = (i *len(expNames))* w + w;
#                j = (i-1) *len(expNames) + len(expNames) * w * 0.5
#        print i-1, len(expNames), w, len(expNames) * w, len(expNames) * w * 0.5
        print j
        xtics.append(j)
    stringXtics=[]
    for i in range(1, len(xtics)+1):
        i = i + DescriptionParser.getMinVarOfExp(expName) - 1;
        stringXtics.append("%d"%i)
   
    name = ParseSaveFileDumpResult.name[pos]
    xlabel = "Number of AIs"
    matplotlib.pyplot.xlabel(xlabel)
#    matplotlib.pyplot.show()
    x = Configuration.moreAICommands
    n = numpy.arange(len(x))
    matplotlib.pyplot.ylabel(name)
#    legend("abc")
    #    matplotlib.pyplot.xticks(n, x)
#    matplotlib.pyplot.show()
    
#            n = numpy.array(DescriptionParser.getFactors(expName))
    n = numpy.array(xtics)
    x = stringXtics
    matplotlib.pyplot.xticks(n, x)
    name = string.replace(name, " ", "_")
    matplotlib.pyplot.savefig("../png/"+ "scalability" + "_median_" + name + "_%d"%pos+".eps")

def time_boxplot2(expName, machineName, col, isShow=False):
    matplotlib.pyplot.clf()
    d = []
    for factor in DescriptionParser.getFactors(expName):
        data = getTimeData2(expName, machineName, col, factor)
        d.append(data)
    return d

def getTimeData2(expName, machineName, col,factor):
    dir = os.path.join("..", "..", cloudPath, expName)
    childDir = os.path.join(dir, "analysis")
    filenameTemplate = config.getCpuMemFileNameTemplate(0, expName, factor)
    data = []
    for filename in os.listdir(childDir):
        if filename.find(filenameTemplate) < 0: 
            continue
        if(filename.find(machineName) < 0):
            continue
        file = open(os.path.join(childDir,filename))
        lines = file.readlines()
        l = lines[len(lines)-1]
        tuple = string.split(l)
        data.append(getFloatCputime(tuple[col]))
    return data


def cpu_walkclock_errorBar2(expName, isShow=False):
    types = ["m1.small", "m1.large", "c1.xlarge"]
#    machineNames = ["ip-10-32-69-4"]
    machineNames = ["ip-10-32-69-4","ip-10-116-150-215", "domU-12-31-39-0B-D1-71"];
    sym = ['*', 'o', '+']
    pth = 0
    pics = []
    plt.figure()
    fontsize = 15
    yoverride = {
       'fontsize'            : fontsize,
       'verticalalignment'   : 'center',
       'horizontalalignment' : 'right',
       "weight":"bold"}
    xoverride = {
    'fontsize'            : fontsize,
    'verticalalignment'   : 'top',
    'horizontalalignment' : 'center',
    'weight':'bold'
    }
    matplotlib.pyplot.axes([0.1,0.1,0.85,0.85],frameon = True) 

    for machineName in machineNames:
#        d = time_boxplot2(expName, machineName, 0, isShow)
    #    matplotlib.pyplot.axes([0.12,0.08,0.8,0.9],frameon = True) 
        dx = [1,2,4,8,16,32,64,128]
        x = np.array([1,2,3,4,5,6,7,8]);
        y= [];
        yerror = [];
        for i in range(0, len(dx)):
            d = getTimeData2(expName, machineName, 0, dx[i])
#            print dx[i]
#            print d
            data = np.array(d);
            mean = np.mean(data);
            standardError = scipy.stats.sem(data);
            y.append(mean)
            yerror.append(standardError);
        
        p,t1,t2 = plt.errorbar(x, np.array(y), yerr=np.array(yerror), marker=sym[pth], label=types[pth])
#        legend(types[pth])
        plt.ylim([0,1600])
        pics.append(p)
        pth = pth + 1
    print len(pics)
    print len(types)    
    plt.legend(pics, types, loc=2)
    suffix(expName, 4, isShow, "" , "", "cpu_walkclock_errorBar")

if __name__ == "__main__":
    cpu_walkclock_errorBar2("1a7", True)
    
#    cpu_usage_mem_boxplot("1a7", False)
#    cpu_walkclock_boxplot("1a7", False)
#    _1a8_cpu_usage_mem_boxplot()
#    _1a11_5y_All(10)
#    getScore("1a8", 10)
#    scalability_all_median(1, False);
#    rondje(1,False)
#    rondje(2,False)
#    rondje(10,True)
#    rondje(11,False)

#    rondjeWhichCompany(10, True, 1)
#    rondjeWhichCompany(10, True, 1)
#    rondje_boxplot(10)

#    rondje(11)
#    expNames = ["quick-1a11_0_0-5y", "quick-1a11_0_1-5y", "quick-1a11_0_2-5y", "quick-1a11_0_3-5y"]
##    expNames = [ "quick-1a14-5y", "quick-1a15-5y"]
#    for expName in expNames:
#        getScore(expName, 10, True)

##        cpu_usage_mem_boxplot(expName, False)
##        cpu_walkclock_boxplot(expName, False)
##        getScore(expName, 1, True)
##        getScore(expName, 2, True)
#        getScore(expName, 10, True)
##        getScore(expName, 11, True)

#1 Number of Vehicles", 2 "Number of Profitable Vehicles"
#    expName = "1a7"
#    cpu_walkclock_boxplot(expName, False)
#    cpu_usage_mem_boxplot(expName, False)
#    getScore(expName, 1, True)
#    getScore(expName, 2, True)
#    expName = "1a2"
#    cpu_walkclock_boxplot(expName, False)
#    cpu_usage_mem_boxplot(expName, False)
    
    
#    expName = "1a6"
#    cpu_walkclock_boxplot(expName, False)
#    expName = "1a6-64"
#    cpu_walkclock_boxplot(expName, False)
#    expName = "1a6-128"
#    cpu_walkclock_boxplot(expName, False)
#    expName = "1a6-256"
#    cpu_walkclock_boxplot(expName, False)
#    expName = "1a6-512"
#    cpu_walkclock_boxplot(expName, False)
#    getScore(expName,10,True)
#    expName = "1a7"
#    getScore(expName, 1, True)
#    getScore(expName, 2, True)
#    expName = "1a5"
#    getScore(expName, 10, True)
#    cpu_usage_mem_boxplot(expName, False)
    
#    expName = "quick-1a15-5y"
#    expNames = ["1a13-6","quick-1a15-5y", "quick-1a14-5y"]
#    for expName in expNames:
#        cpu_usage_mem_boxplot(expName, False)
#        cpu_walkclock_boxplot(expName, False)
#        getScore(expName, 1, True)
#        getScore(expName, 2, True)
#        getScore(expName, 10, True)
#        getScore(expName, 11, True)

#    getScore("1a7",1)
#    getScore("1a7",2)

#    getNodeNameInAutoSave("1a10")
#    for i in range(1,12):   
#            getScore("1a10",i)
#    plot("1a4", 453)
#    expNames = ["1a3"]
#    expNames = ["1a7"]
#    print len(HowmanyExps())
#    expNames = ["1a5"]
#    getScore("1a5",10)
#    getScore("1a5",9)
#    for expName in expNames:
#        for i in range(1,12):   
#            getScore(expName,i)
#        cpu_usage_mem_boxplot(expName, False)
#        cpu_usage_mem_min_median_max_timeseries(expName, False)
#        cpu_walkclock_boxplot(expName, False)
#        cpu_time_boxplot(expName, False)
    
#    for i in range(1,12):
#        getScore("1a7-5",i)
#    
#    for i in range(1,12):
#        getScore("1a7-5-1024",i)
#
#    for expName in ["1a3"]:
#        cpu_usage_mem_boxplot(expName, False)
#        cpu_usage_mem_min_median_max_timeseries(expName, False)
#        cpu_walkclock_boxplot(expName, False)
#        cpu_time_boxplot(expName, False)
        
#    for i in range(1,28):
#        plotTwoDataTogether(601, "4a7", i, 0, 800, True)
#    plot("4a7", 601)
#    expName = "1a5"
#    plotComparing(0, expName, 1, 1, DescriptionParser.getMinVarOfExp(expName), DescriptionParser.parseConfigureFile(expName), "", 0, 900, True)
    expName = "4a7"
    from matplotlib import rc
#    rc('font',  family='serif', style='normal', variant='normal',
#        stretch='normal', size='25')#weight='bold', 


#    expId = 601
#    cpu_usage_mem_boxplot(expName, True, True)
#    plotNetworkTogether(expId, expName, 1, 1, 1, 5, "", 0, 800, True)
##    plotNetworkTogether(expId, expName, 1, 1, 6, 10, "", 50, 800, True)
#    plotNetworkTogether(expId, expName, 1, 1, 20, 25, "", 0, 800, True)
#    
#    
#    ps.set_mode("medium")
#    pylab.figure(1)

#    expName = "4a7-1024"
#    cpu_usage_mem_boxplot(expName, False, True)
    
    
#    expId = 601
#    plotNetworkTogether(expId, expName, 1, 1, 1, 5, "", 100, 810, 1, 10000, True,False)
####    plotNetworkTogether(expId, expName, 1, 1, 6, 10, "", 50, 800, True)
#    plotNetworkTogether(expId, expName, 1, 1, 21, 25, "", 100, 810,0, 200000, True,False)
#    
#    plotComparing(0, expName, 1, 1, 21, 40, "", 0, 1400, True)
    
    #Net to check
#    network_byte_packet_boxplot("4a7", False)

#    for expName in ["1a10"]:
#        cpu_usage_mem_boxplot(expName, False)
##        cpu_usage_mem_min_median_max_timeseries(expName, False)
#        cpu_walkclock_boxplot(expName, False)
#        cpu_time_boxplot(expName, False)
#    _1a8_cpu_usage_mem_boxplot(False)


#    plotComparing(0, expName, 1, 1, 41, 60, "", 0, 1400, True)
#    plotComparing(0, expName, 1, 1, 61, 80, "", 0, 1400, True)
#    plotComparing(0, expName, 1, 1, 81, 92, "", 0, 1400, True)
#    plot("1a4", 0)
#    analysisTimeFactor("1a4")
#    for expName in ["1a1", "1a2", "1a3", "1a4", "1a5", "1a6", "1a7", "1a8"]:
#    for expName in ["1a7"]:
#        cpu_usage_mem_boxplot(expName, False)
#        cpu_usage_mem_min_median_max_timeseries(expName, False)
#        cpu_walkclock_boxplot(expName, False)
#        cpu_time_boxplot(expName, False)
#    player_per_tiles_cpu_time_walkclock_barplot(False)
#    cpu_time_linear_prediction("1a7", False)
#    cpu_walkclocktime_linear_prediction("1a7", False)
#    cpu_time_linear_prediction("1a2", False)
#    cpu_walkclocktime_linear_prediction("1a2", False)

#    minMaxPlotOfSingleFactor(101, "1a1", 16, 1)
#    difference("1a5")
#    player_per_tiles_cpu_time_walkclock_barplot(False)